﻿using System;
using System.Collections.Generic;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class SearchDAO
    {
        private List<vRoomInfo> EnsureRoom(DateTime inDate, DateTime outDate)
        {
            using (var ctx = new BlueMDataContext())
            {
                List<vSearchRoom> usearchRooms = ctx.vSearchRooms.Where(
                    p =>
                    (outDate <= p.CheckOutDate && outDate >= p.CheckInDate) ||
                    (inDate <= p.CheckOutDate && inDate >= p.CheckInDate) ||
                    (inDate <= p.CheckInDate && outDate >= p.CheckOutDate)).OrderBy(p => p.RoomID).ToList();

                List<vRoomInfo> roomInfos = ctx.vRoomInfos.ToList();

                foreach (vSearchRoom t in usearchRooms)
                {
                    for (int i = 0; i < roomInfos.Count; i++)
                    {
                        if (roomInfos[i].RoomID != t.RoomID) continue;
                        roomInfos.RemoveAt(i);
                        break;
                    }
                }

                return roomInfos;
            }
        }

        public List<int> AvailableRoomIDs(DateTime inDate, DateTime outDate)
        {
            return EnsureRoom(inDate, outDate).Select(p => p.RoomID).ToList();
        }

        public List<vRoomInfo> SearchRooms(DateTime inDate, DateTime outDate, int roomTypeId, int minPrice, int maxPrice,
                                           bool view, bool bath, bool balcony)
        {
            List<vRoomInfo> infos = EnsureRoom(inDate, outDate);
            if (roomTypeId > 0)
                infos = infos.Where(p => p.RoomTypeID == roomTypeId).ToList();
            if (minPrice > 0)
                infos = infos.Where(p => p.RoomPrice >= minPrice).ToList();
            if (maxPrice > 0)
                infos = infos.Where(p => p.RoomPrice <= maxPrice).ToList();
            if (view)
                infos = infos.Where(p => p.View).ToList();
            if (bath)
                infos = infos.Where(p => p.Bath).ToList();
            if (balcony)
                infos = infos.Where(P => P.Balcony).ToList();

            return infos;
        }
    }
}